import sys

import pymysql
from PyQt5.QtCore import Qt

import cv2
import face_recognition
import os
from find import cha
from PyQt5.QtWidgets import QApplication, QMessageBox

from ui.zhu import Ui_MainWindow
from PyQt5 import QtCore, QtGui, QtWidgets
from sign_up import zc



class qw(QtWidgets.QMainWindow,Ui_MainWindow):
    def __init__(self):
        super(qw,self).__init__()
        self.setWindowFlags(Qt.WindowMinimizeButtonHint)
        self.setupUi(self)
        self.label.setScaledContents(True)  # 图片自适应
        self.update_timer = QtCore.QTimer()  # 设置定时器
        self.video_path = 0
        self.capture = cv2.VideoCapture(self.video_path)
        self.capture.set(6, cv2.VideoWriter.fourcc('M', 'J', 'P', 'G'))
        self.capture.set(3, 480)
        self.capture.set(4, 640)
        self.name = '123'
        self.she =  False
        self.zhao = False
        self.kai=True
        self.InitSold()


    def InitSold(self):
        self.pushButton.clicked.connect(self.shibie) #识别
        self.pushButton_2.clicked.connect(self.guan) #关闭
        self.pushButton_3.clicked.connect(self.zc)  #注册
        self.update_timer.timeout.connect(self.show_camera)  #定时器
        self.pushButton_4.clicked.connect(self.open)  #打开摄像头
    #打开摄像头
    def open(self):
        self.update_timer.start(30)
        self.she=True
    #定时器，打开摄像头
    def show_camera(self):
        ret, self.frame = self.capture.read()
        # 原始图像显示
        self.srcFrame = cv2.resize(self.frame,
                                   (self.label.width(), self.label.height()))  # 把读到的帧的大小重新设置为 640x480
        self.srcFrame = cv2.cvtColor(self.srcFrame, cv2.COLOR_BGR2RGB)  # 视频色彩转换回RGB，这样才是现实的颜色
        self.srcFrame = QtGui.QImage(self.srcFrame.data, self.srcFrame.shape[1], self.srcFrame.shape[0],
                                     int(self.srcFrame.shape[1]) * 3,
                                     QtGui.QImage.Format_RGB888)  # 把读取到的视频数据变成QImage形式
        self.label.setPixmap(QtGui.QPixmap.fromImage(self.srcFrame))  # 往显示视频的Label里 显示QImage
    #注册
    def zc(self):
        if self.she==True:
            save_path = r"D:\python_Project\FACE\face_images"
            if not os.path.exists(save_path):
                os.makedirs(save_path)
            # 创建连接
            conn = pymysql.connect(
                host='localhost',  # 主机名
                port=3306,  # 端口号
                user='root',  # 用户名
                password='xjy123456',  # 密码
                autocommit=True  # 自动提交更改
            )
            # 创建游标
            cursor = conn.cursor()
            conn.select_db('face_recognition')
            # 执行SQL查询
            sql = "SELECT COUNT(*) FROM face"
            cursor.execute(sql)
            # 获取查询结果
            result = cursor.fetchone()
            # 关闭游标和连接
            cursor.close()
            conn.close()

            ret, frame = self.capture.read()
            photo_name = os.path.join(save_path, f"{result[0]}.png")
            cv2.imwrite(photo_name, frame)

            self.one=zc(result[0])
            self.one.show()
        else:
            QMessageBox.information(self, "提示", "请打开摄像头", QMessageBox.Ok)


    def guan(self):
        self.close()
        self.capture.release()

    def shibie(self):
        if self.she==True:  #判断摄像头是否打开
            ret, frame = self.capture.read()
            path = r'D:\python_Project\FACE\face_images'  # 模型数据图片目录
            total_image_name = []
            total_face_encoding = []
            self.name ='123'
            self.num=0
            self.kai=True

            while self.kai==True and self.num<10:
                for fn in os.listdir(path):  # fn 表示的是文件名q
                    try:
                        total_face_encoding.append(face_recognition.face_encodings(face_recognition.load_image_file(path + "/" + fn))[0])
                        fn = fn[:(len(fn) - 4)]  # 截取图片名（这里应该把images文件中的图片名命名为为人物名）
                        total_image_name.append(fn)  # 图片名字列表
                        print(fn)
                    except:
                        continue
                # 发现在视频帧所有的脸和face_enqcodings
                face_locations = face_recognition.face_locations(frame)
                face_encodings = face_recognition.face_encodings(frame, face_locations)
                # 在这个视频帧中循环遍历每个人脸
                for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
                    # 看看面部是否与已知人脸相匹配。
                    for i, v in enumerate(total_face_encoding):
                        match = face_recognition.compare_faces([v], face_encoding, tolerance=0.5)
                        print('12')
                        if match[0]:
                            self.name = total_image_name[i]
                            self.zhao=True #找到了
                            self.kai=False #退出循环的信号
                            break
                    if self.kai==False or self.zhao==True:
                        break
                    else:
                        pass
                self.num+=1
            if self.name!='123':
                self.two=cha(self.name)
                self.two.show()
            else:
                QMessageBox.information(self, "提示", "未检测到注册过的人脸", QMessageBox.Ok)

        else:
            QMessageBox.information(self, "提示", "请打开摄像头", QMessageBox.Ok)




if __name__ == '__main__':
    QApplication.setHighDpiScaleFactorRoundingPolicy(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)
    # 适应高DPI设备
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    # 解决图片在不同分辨率显示模糊问题
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = qw()
    MainWindow.show()
    sys.exit(app.exec_())
